<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-remove="handleRemove"
      :file-list="fileList"
      list-type="picture-card"
      :auto-upload="false"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fileList: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }, { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }]
    }
  },
  methods: {
    //   submitUpload() {
    //     this.$refs.upload.submit();
    //   },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    submitUpload() {
      const _self = this
      // let names = Array.prototype.map.call(this.$refs.upload.uploadFiles,(i,e)=>i.name);
      // console.log(this.$refs.upload.uploadFiles)
      if (this.$refs.upload.uploadFiles.length === 0) { return false }
      for (let k = 0; k < this.$refs.upload.uploadFiles.length; ++k) {
        try {
          var file = _self.$refs.upload.uploadFiles[k].name
          if (file === undefined) {
            // return _self.$refs.upload.uploadFiles
            // this.$refs.upload.uploadFiles.splice(k,1)
          } else {
            console.log(this.$refs.upload.uploadFiles)
            var getSuffix = function(fileName) {
              var pos = fileName.lastIndexOf('.')
              var suffix = ''
              if (pos !== -1) {
                suffix = fileName.substring(pos)
              }
              return suffix
            }
            // 利用时间戳生成uuid
            var d = new Date().getTime()
            if (window.performance && typeof window.performance.now === 'function') {
              d += performance.now() // use high-precision timer if available
            }
            var uuid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
              var r = (d + Math.random() * 16) % 16 | 0
              d = Math.floor(d / 16)
              return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
            })
            // 定义文件名
            var filename = uuid + getSuffix(file)
            // 注意formData里append添加的键的大小写
            var formData = new FormData()
            // 存储在oss的文件路径
            formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid)
            // accessKeyId
            formData.append('key', _self.aliyunOssToken.dir + '/' + filename)
            // policy
            formData.append('policy', _self.aliyunOssToken.policy)
            // 签名
            // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
            formData.append('Signature', _self.aliyunOssToken.signature)
            // 文件详情
            formData.append('file', _self.$refs.upload.uploadFiles[k].raw)
            // 成功后返回的操作码
            formData.append('success_action_status', 200)
            var url = _self.aliyunOssToken.host
            var fileUrl = _self.aliyunOssToken.host + '/' + _self.aliyunOssToken.dir + '/' + filename
            $.ajax({
              url: url,
              type: 'POST',
              data: formData,
              async: false,
              cache: false,
              contentType: false,
              processData: false,
              success: function(data) {
                // console.log(fileUrl);
                console.log(data)
              },
              error: function(data) {
                console.log(data)
              }
            })
            this.imgFlag.push('/' + _self.aliyunOssToken.dir + '/' + filename)
          }
        } catch (e) {
          return ''
        }
      }
      return this.imgFlag
    }
  }
}
</script>
